package com.itboye.hutouben.util;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;

import com.itboye.hutouben.base.MyApplcation;
import com.itboye.hutouben.bean.AvatarBeans;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;


/**
 * Created by itboye on 2016/12/9.
 */

public class UploadImage {
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private ExecutorService executorService;
    private static UploadImage upload;
    //图片网络地址

    private String UploadImaeUrl=Const.IMAGE_URL;
    String	 time = String.valueOf((int) (Math.random() * 10));

    private UploadImage() {
        executorService = Executors.newFixedThreadPool(4);
    }

    /**
     * 单例
     *
     * @return
     */
    public static synchronized UploadImage getInstance() {
        if (upload == null) {
            upload = new UploadImage();
        }

        return upload;
    }

    public void execute(final String url, final OnUploadlistener uploadListener) {
        executorService.execute(new Runnable() {

            @Override
            public void run() {

                Handler handler = new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(android.os.Message msg) {
                        switch (msg.what) {
                            case 0:
                                String resultData = msg.getData().getString("result");
                                // requestCode =
                                // msg.getData().getInt("requestCode");
                                uploadListener.OnSuccess(resultData);
                                break;
                            case 1:
                                String errorInfo = "上传失败";
                                uploadListener.OnError(errorInfo);
                                break;
                            default:
                                break;
                        }

                    }
                };

                try {
                    OkHttpClient client = new OkHttpClient();
                    client.setConnectTimeout(10, TimeUnit.SECONDS);
                    client.setReadTimeout(10, TimeUnit.SECONDS);
                    client.setWriteTimeout(10, TimeUnit.SECONDS);

                    File file = new File(url);
                    // 创建请求BODY
                    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                            .addFormDataPart("uid", "34")
                            .addFormDataPart("type", "avatar")
                            .addFormDataPart("notify_id", (String) SPUtils.get(MyApplcation.ctx, null, time, ""))
                            .addFormDataPart("image", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)).build();

                    Request request = new Request.Builder()///File/upload?access_token=ACCESS_TOKEN by565fa4facdb191
                            .url(UploadImaeUrl)
                            .post(requestBody).build();

                    Response response = client.newCall(request).execute();
                    if (!response.isSuccessful()) {
                        handler.sendEmptyMessage(1);
                    } else {
                        String result = response.body().string();
                        System.out.println("图片上传的结果" +
                                ""+result);

                        Gson gson = new Gson();
                        AvatarBeans avatarBeans = gson.fromJson(result, AvatarBeans.class);// 获取到网络端数据,多个参数
                        if (avatarBeans.getCode() == 0) {
                            Log.e("123","123");
                            Message msg = new Message();
                            msg.what = 0;
                            Bundle bundle = new Bundle();
                            bundle.putString("result", avatarBeans.getData().getUid());
                            System.out.println("图片路径"+avatarBeans.getData().getId());
                            SPUtils.put(MyApplcation.ctx, null, Const.URL, avatarBeans.getData().getId());
                            msg.setData(bundle);
                            handler.sendMessage(msg);
                            String url = (String) SPUtils.get(MyApplcation.ctx, null, Const.AVATAR_URL, "");
                            if (!url.equals("")) {
                                SPUtils.remove(MyApplcation.ctx, null, Const.AVATAR_URL);
                            }
                            SPUtils.put(MyApplcation.ctx, null, Const.AVATAR_URL, avatarBeans.getData().getId());
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

        });
    }

    /**
     *
     * @author winter 要实现的接口
     */

    public interface OnUploadlistener {

        public void OnSuccess(String resultData);

        public void OnError(String resultData);

    }
}
